<template>
  <div>
    <h5 class="text-muted">当前任务：信用评级</h5>
    <el-form class="query-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="企业名称查询"
          :clearable="true"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="params.has_ele_fee"
          border
          :true-label="1"
          false-label=""
          @change="getData"
        >
          有电表
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>
    </el-form>
    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column label="企业名称" min-width="180" prop="customer_name"></el-table-column>
        <el-table-column label="地址" min-width="140" prop="address">
          <template slot-scope="scope">
            <span class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</span>
          </template>
        </el-table-column>
        <el-table-column label="组织形式" min-width="110" prop="org_class_name"></el-table-column>
        <el-table-column label="企业类型">
          <template slot-scope="scope">
            {{ enumFarmType[scope.row.farm_type] }}
          </template>
        </el-table-column>

        <el-table-column label="法人" prop="corp_name"></el-table-column>
        <el-table-column label="联系电话" min-width="100" prop="mobile_no"></el-table-column>

        <el-table-column label="产品名字" align="center" min-width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.load_type }}-{{ scope.row.load_name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="分配时间" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.taskAssginDate }}</span>
          </template>
        </el-table-column>

        <el-table-column label="调查完成时间" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.taskCompleteDate }}</span>
          </template>
        </el-table-column>

        <el-table-column label="完成天数" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.completeDays }}</span>
          </template>
        </el-table-column>

        <el-table-column label="申请金额(万元)" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.apply_funds }}</span>
          </template>
        </el-table-column>

        <el-table-column label="预审金额(万元)" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.approved_funds }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="评级状态">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.ratingType">{{ scope.row.ratingStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120">
          <template slot-scope="scope">
            <div v-if="powerHide">
              <el-tooltip content="查看档案" effect="dark" placement="bottom">
                <el-button class="py-0 px-2" type="text" @click="goInfo(scope.row)">
                  <i class="fa fa-search"></i>
                </el-button>
              </el-tooltip>
            </div>
            <div v-else-if="scope.row.is_need_rating === '2'">
              <el-tooltip
                content="去评级"
                v-if="job === 'org_credit_super'"
                effect="dark"
                placement="bottom"
              >
                <el-button class="py-0 px-1" type="text" @click="goRatingResult(scope.row)">
                  <i class="fa fa-edit"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="查看档案" effect="dark" placement="bottom">
                <el-button class="py-0 px-2" type="text" @click="goInfo(scope.row)">
                  <i class="fa fa-search"></i>
                </el-button>
              </el-tooltip>
            </div>
            <!--<div v-else-if="">-->
            <!--<el-dropdown trigger="click"-->
            <!--@command="c=>handleCommand(c, scope.row.customer_related_id, scope.row.customer_id)">-->
            <!--<el-button size="mini"-->
            <!--:type="scope.row.ratingType">-->
            <!--是否评级 <i class="fa fa-angle-down"></i>-->
            <!--</el-button>-->
            <!--<el-dropdown-menu slot="dropdown">-->
            <!--<el-dropdown-item :command="1">是 (生成评级报告)</el-dropdown-item>-->
            <!--<el-dropdown-item :command="3">否 (不需要评级)</el-dropdown-item>-->
            <!--</el-dropdown-menu>-->
            <!--</el-dropdown>-->
            <!--</div>-->

            <div v-else>
              <el-tooltip content="去评级" effect="dark" placement="bottom">
                <el-button class="py-0 px-1" type="text" @click="goRating(scope.row)">
                  <i class="fa fa-edit"></i>
                </el-button>
              </el-tooltip>

              <el-tooltip content="查看档案" effect="dark" placement="bottom">
                <el-button class="py-0 px-2" type="text" @click="goInfo(scope.row)">
                  <i class="fa fa-search"></i>
                </el-button>
              </el-tooltip>

              <el-tooltip content="评级明细" effect="dark" placement="bottom">
                <el-button v-if="admin" class="py-0 px-2" type="text">
                  <i class="fa fa-file-text-o"></i>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="query-pagination">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :current-page.sync="params.index"
          :page-size="params.size"
          :total="totalCount"
          @current-change="getData"
        ></el-pagination>
      </div>
    </loading-wrap>

    <el-dialog
      width="80%"
      top="30px"
      :close-on-click-modal="false"
      :before-close="closeReportView"
      :visible.sync="reportView"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="信用档案" name="first">
          <credit-file
            :view-mode="true"
            v-if="reportView"
            :related-id="customerRelatedId"
          ></credit-file>
        </el-tab-pane>
        <el-tab-pane label="调查报告" name="second">
          <!-- <prcatise :view-mode="true"
                    :related-id="customerRelatedId"></prcatise> -->
          <census-report :view-mode="true" :related-id="customerRelatedId"></census-report>
        </el-tab-pane>
        <!--v-if="showRatingReport"-->
        <el-tab-pane label="评级结果" v-if="!isSimpleReport" name="third">
          <task-rating-result
            :view-mode="true"
            :related-id="customerRelatedId"
          ></task-rating-result>
        </el-tab-pane>

        <el-tab-pane label="评级报告" v-if="showRatingReport && !isSimpleReport" name="fouth">
          <task-rating-report
            :view-mode="true"
            :related-id="customerRelatedId"
          ></task-rating-report>
        </el-tab-pane>

        <el-tab-pane label="附件" name="fifth">
          <attach-list :data-list="dataList"></attach-list>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>
<script>
import { deltaDay } from '@/common/plugins/tools/date'
import { arrayFromString } from '@vimi/utils-tool'

import CreditFile from '@/credit/components/creditFile/Index'
import AttachList from './AttachList'
import TaskRatingReport from './TaskRatingReport'
import TaskRatingResult from './TaskRatingResult'
// import Prcatise from './Prcatise'
import CensusReport from '@/credit/views/city/task/CensusReport'
import { enumFarmType, enumRatingStatus } from '@/credit/plugins/enum'

export default {
  components: {
    CreditFile,
    // Prcatise,
    CensusReport,
    AttachList,
    TaskRatingReport,
    TaskRatingResult,
  },
  props: {},
  data() {
    return {
      enumFarmType,
      enumRatingStatus,
      enumStatusType: {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger',
      },
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        'is_need_rating.eq': 1,
        'project_status.eq': 3,
        'rating_status.eq': '',
        // 'rating_status.neq': '3'
      },
      totalCount: 0,
      tableData: [],
      file: 0,
      reportView: false,
      activeName: 'first',
      dataList: [],
      customerRelatedId: '',
      ratingStatus: 1,
      // 报告表
      reportTableName: 'credit_level_report',
      isSimpleReport: true,
    }
  },
  computed: {
    job() {
      return this.$store.getters.user.job
    },
    admin() {
      return this.job === 'org_corp'
    },
    powerHide() {
      return (
        [
          'org_c_manage',
          'org_c_emp',
          'org_r_manage',
          'org_r_emp',
          'org_c_general',
          'org_c_general_emp',
          'org_corp',
        ].indexOf(this.job) > -1
      )
    },
    showRatingReport() {
      return this.ratingStatus === 1 || this.ratingStatus === 2
    },
  },
  watch: {
    $route(route) {
      if (route.name === 'taskRating') {
        this.getData()
      }
    },
  },
  created() {
    this.userId = this.$store.getters.user.userId
    this.params['service_id.eq'] = this.$store.getters.org.clientId
    this.getData()
  },
  activated() {},
  mounted() {},
  methods: {
    getData() {
      const params = { ...this.params }
      let status = this.$route.query.status
      if (status === undefined) {
        status = ''
        params['rating_status.neq'] = 3
      }
      params['rating_status.eq'] = status

      if (
        [
          'org_credit_super',
          'org_c_manage',
          'org_r_emp',
          'org_r_manage',
          'org_corp',
          'org_p_manage', // 信用评级负责人
        ].indexOf(this.job) < 0
      ) {
        params['orWhere.res_a.eq'] = this.userId
        params['orWhere.res_b.eq'] = this.userId
      }

      this.$api
        .getData('credit', 'customer_related_view', params, {
          create_time: 'desc',
        })
        .then(res => {
          const data = res.data.data || []
          this.tableData = data.map(item => {
            item.ratingStatus = enumRatingStatus[item.rating_status]
            item.ratingType = this.enumStatusType[item.rating_status] || 'info'

            item.taskAssginDate = this.$utils.dateFormat(item.task_assgin_date, 'yyyy.MM.dd')
            item.taskCompleteDate = this.$utils.dateFormat(item.task_complete_date, 'yyyy.MM.dd')
            const days = deltaDay(item.task_assgin_date, item.task_complete_date)
            item.completeDays = days ? `${days}天` : ''

            return item
          })
          this.totalCount = res.data.totalCount
        })
    },

    goRating(data) {
      sessionStorage.setItem('credit_task_router', 'rating')
      this.$router.push({
        name: 'taskRatingEdit',
        query: {
          id: data.customer_related_id,
        },
      })
    },
    goRatingResult(data) {
      sessionStorage.setItem('ratingStatus', data.rating_status)
      sessionStorage.setItem('credit_task_router', 'rating')
      this.$router.push({
        name: 'taskRatingResult',
        query: {
          id: data.customer_related_id,
        },
      })
    },
    closeReportView() {
      this.reportView = false
      this.activeName = 'first'
    },

    goInfo(data) {
      this.customerRelatedId = data.customer_related_id
      this.ratingStatus = +data.rating_status
      this.isSimpleReport = data.is_simple_process === '1'
      this.getAttachment()
      sessionStorage.setItem('customer_related_id', this.customerRelatedId)
      this.file++
      this.reportView = true
    },

    getAttachment() {
      this.dataList = []
      this.$api
        .getData(
          'credit',
          'datum_customer_attachment',
          {
            'customer_related_id.eq': this.customerRelatedId,
          },
          { create_time: 'desc' }
        )
        .then(res => {
          if (!res || !res.data) {
            return
          }
          for (let p of res.data) {
            const images = arrayFromString(p.attachment)
            this.dataList.push({
              src: images,
              time: this.$utils.dateFormat(p.create_time, 'yyyy.MM.dd'),
              name: p.attachment_type,
            })
          }
        })
    },

    async handleCommand(status, id, customerId) {
      // 要做的事情：
      // 1 判断当前 customer_realted_id 是否 credit_level_report 表中存在
      // 2 如果存在，修改rating_status值为参数status的值
      // 3 如果不存在，创建一个，其参数有 {customer_id、customer_related_id、rating_status}
      //   其中rating_status的值为1（参数status的值）
      const [res, err] = await this.$utils.promise(
        this.$api.getData('credit', this.reportTableName, {
          index: 1,
          size: 1,
          'customer_related_id.eq': id,
        })
      )

      if (err) {
        return this.$message.error(`获取信用评级报告信息失败！(${err ? err.status : ''})`)
      }

      let r2 = null
      if (res && res.data && res.data.data && res.data.data.length) {
        // 报告存在，修改状态
        ;[r2] = await this.$utils.promise(
          this.$api.updateData('credit', 'customer_related', id, {
            rating_status: status,
          })
        )
      } else {
        // 报告不存在，添加
        ;[r2] = await this.$utils.promise(
          this.$api.addData('credit', this.reportTableName, {
            customer_id: customerId,
            customer_related_id: id,
            rating_status: status,
          })
        )
      }

      if (!r2) {
        return this.$message.error('修改失败，请重试！')
      }

      this.$message.success('报告确认成功！')
      this.getData()
    },
  },
}
</script>
<style scoped>
.text-num {
  font-size: 1.25rem;
  font-weight: bold;
}
</style>
